package 动态数组;

import java.util.Arrays;

public class DynamicArrayImpl implements IDynamicArray {
    public static final int DEFAULT_CAPACITY = 10;
    private int size;
    private int[] list;
    DynamicArrayImpl(int capacity){
        capacity = (capacity < DEFAULT_CAPACITY) ? DEFAULT_CAPACITY : capacity;
        this.list = new int[capacity];
    }
    DynamicArrayImpl(){
        this.list = new int[DEFAULT_CAPACITY];
    }


    @Override
    public void insert(int index, int element) {
        if(index <= 0) index = 0;
        if(index > size) index = size;
        // 尾插入
        if(index == size){
            list[index] = element;
            size++;
            return;
        }
        // 其他插入
        for (int i=size;i>index;i--){
            list[i] = list[i-1];
        }
        list[index] = element;
        size++;

    }

    @Override
    public void add(int element) {
        this.insert(size,element);
    }

    public void shift(int element){
        this.insert(0,element);
    }

    @Override
    public void remove(int index) {
        if(size == 0) {
            throw new IndexOutOfBoundsException("没有元素");
        }
        if(index < 0) index = 0;
        // 尾删除
        if(index >= size-1) {
            size--;
            return;
        }
        // 其他删除
        for(int i=index;i<size-1;i++){
            list[i] = list[i+1];
        }
        size--;


    }

    @Override
    public Boolean isEmpty() {
        return this.size == 0;
    }

    @Override
    public Boolean contains(int element) {
        return indexOf(element) != -1;
    }

    @Override
    public void clear() {
        this.size = 0;
    }

    @Override
    public int set(int index, int element) {
        if(index < 0 || index >= size){
            throw new IndexOutOfBoundsException("index超出范围:"+index+ " size:"+this.size);
        }
        int old = this.list[index];
        this.list[index] = element;
        return old;
    }

    @Override
    public int get(int index) {
        if(index < 0 || index >= size){
            throw new IndexOutOfBoundsException("index超出范围:"+index+ " size:"+this.size);
        }
        return this.list[index];
    }

    @Override
    public int indexOf(int element) {
        for(int i=0;i<size;i++){
            if(list[i] == element) return i;
        }
        return -1;
    }

    @Override
    public int size() {
        return this.size;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("DynamicArrayImpl{ ").append("size=").append(size).append(", list= [");
        for(int i=0;i<size;i++){
            stringBuilder.append(list[i]);
            if(i != size-1){
                stringBuilder.append(", ");
            }

        }
        stringBuilder.append("] }");
        return stringBuilder.toString();
    }
}
